import { request } from 'umi';
import { setOnlineToken } from '@/services/onlineAuth';
import { decryptByDES } from '@/utils';
import notify from 'devextreme/ui/notify';
// const ROOT = '/cpsapis';
// const ROOT = 'http://49.4.51.190:8000';
const ROOT = 'http://localhost:8070';  // oracle 版本


/** 登录接口 需要返回 Response */
async function login(body: any, loginHeader: any): Promise<API.SerResult> {
    const r = await request(`${ROOT}/user/login`, {
        // const r = await request(`${ROOT}/auth/login`, {
        method: 'POST',
        getResponse: true,
        headers: {
            'Content-Type': 'application/json',
            ...loginHeader,
        },
        data: body,
    });
    const { data, response } = r;
    if (data.ok) {
        setOnlineToken(response.headers.get('cpasToken')!);
        return data;
    }
    return r.data;
}

/** 退出接口 */
async function logout(): Promise<API.SerResult> {
    return await request<API.SerResult>(`${ROOT}/user/logout`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
    });
}

/** 获取当前用户信息 接口 */
async function getUserInfo(): Promise<API.SerResult> {
    const r = await request<API.SerResult>(`${ROOT}/user/getUserInfo`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
    });
    if (r.ok) {
        return r;
    }
    const localStorageData: any = localStorage.getItem('cpasUserInfo');
    const { usercode, aesPassword } = JSON.parse(localStorageData) as any;
    const tempPassword = decryptByDES(aesPassword);
    try {
        const res = await login({ usercode, password: tempPassword }, {});
        if (res.ok) {
            return res;
        } else {
            notify({ message: res.data, position: 'top center', width: 600 }, "error", 3000);
            return res;
        }
    } catch (errors) {
        notify({ message: errors, position: 'top center', width: 600 }, "error", 3000);
    }
}

/**
 * 获取 sql 模板接口数据
 * @param apiName api名称
 * @param params 发送参数，一般都为 JSON格式
 * @returns ServerResult
 */
export async function onlineGetApiData(apiName: string, params?: any): Promise<API.SerResult> {
    const pd: API.PostData = {
        name: apiName,
    };
    if (params) {
        pd.params = params;
    }
    // return request<API.SerResult>(`${ROOT}/cpasApi/update`, { // 电子档案
    try {
        const r = await request<API.SerResult>(`${ROOT}/cloudServerApi/sqlapis/getApiData`, {
            // 云转平台
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: pd,
        });
        if (r.ok) {
            return r;
        }
        if (r.data === 'loginSucess') {
            const localStorageData: any = localStorage.getItem('cpasUserInfo');
            const { usercode, aesPassword } = JSON.parse(localStorageData) as any;
            const tempPassword = decryptByDES(aesPassword);
            try {
                const res = await login({ usercode, password: tempPassword }, {});
                if (res.ok) {
                    await onlineGetApiData(apiName, params);
                } else {
                    notify({ message: res.data, position: 'top center', width: 600 }, "error", 3000);
                }
            } catch (errors) {
                notify({ message: errors, position: 'top center', width: 600 }, "error", 3000);
            }
        }
    } catch (error) {
        return Promise.resolve({ data: error, ok: false, code: 100000 });
    }
}

export async function onlineGetApisData(params?: any): Promise<API.SerResult> {
    try {
        const res = await request<API.SerResult>(`${ROOT}/cloudServerApi/sqlapis/getApisData`, {
            // 云转平台
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: params,
        });
        if (res.code !== 0) {
            // console.log(`请求返回错误,code为：${res.code}`);
        }
        return res;
    } catch (error) {
        return Promise.resolve({ data: error, ok: false, code: 100000 });
    }
}



export { login, logout, getUserInfo };
